package com.sap.jcp.sm.web;

import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.apache.struts2.interceptor.RequestAware;
import org.apache.struts2.interceptor.SessionAware;
import org.hsqldb.lib.StringUtil;

import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
import com.sap.jcp.sm.dao.ConfigDAO;
import com.sap.jcp.sm.dao.ConfigDAOImpl;
import com.sap.jcp.sm.dao.ShiftDAO;
import com.sap.jcp.sm.dao.ShiftDAOImpl;
import com.sap.jcp.sm.dao.TrackDAO;
import com.sap.jcp.sm.dao.TrackDAOImpl;
import com.sap.jcp.sm.dao.UserDAO;
import com.sap.jcp.sm.dao.UserDAOImpl;
import com.sap.jcp.sm.domain.Config;
import com.sap.jcp.sm.domain.Shift;
import com.sap.jcp.sm.domain.Track;
import com.sap.jcp.sm.domain.User;
import com.sap.jcp.sm.dto.UserTimelineDTO;
import com.sap.jcp.sm.email.util.ApplicationConfiguraion;
import com.sap.jcp.sm.email.util.EmailManager;
import com.sap.jcp.sm.util.DateUtil;
import com.sap.jcp.sm.util.MappingUtil;

public class UserAction extends ActionSupport implements ModelDriven<User>, SessionAware, RequestAware {

	Map sessionMap;
	Map request;
	private static final long serialVersionUID = 1L;
	private static final String LOGINSUCCESS = "loginsuccess";
	private User user = new User();
	private List<User> pendingUserList = new ArrayList<User>();
	private List<User> userList = new ArrayList<User>();
	private UserDAO userDAO = new UserDAOImpl();
	private TrackDAO trackDAO = new TrackDAOImpl();
	private ShiftDAO shiftDAO = new ShiftDAOImpl();
	private ConfigDAO configDAO = new ConfigDAOImpl();
	private String message;
	
	public String getMessage() {
		return message;
	}

	public void setMessage(String message) {
		this.message = message;
	}

	@Override
	public void validate() {
		if (StringUtil.isEmpty(user.getName())) {
			super.addActionError("User Name required.");
		}
		
		if (StringUtil.isEmpty(user.getEmailId())) {
			super.addActionError("Email Id required.");
		}
		if (StringUtil.isEmpty(user.getPhoneNumber())) {
			super.addActionError("Phone Number required.");
		}
		if (sessionMap.get("admin") == null) {
			if (StringUtil.isEmpty(user.getPassword())) {
				super.addActionError("Password required.");
			}
			
			if (!StringUtil.isEmpty(user.getPassword()) && !StringUtil.isEmpty(user.getConfPassword()) && !user.getPassword().equals(user.getConfPassword())) {
				super.addActionError("Password doesn't Match.");
			}
		}
	}

	public User getModel() {
		return user;
	}
	public String login(){
		//user.setPassword(Encrypt.decryptString(user.getPassword()));
		User loginUser = userDAO.loginUser(user);
		if (loginUser != null) {
			sessionMap.put("user", loginUser);
			sessionMap.put("isUserLoggedIn", "true");
			if (loginUser.getDesignation() != null && (loginUser.getDesignation().contains("Manager") ||  loginUser.getDesignation().contains("Director"))){
				sessionMap.put("admin", "true");
				refreshDetails();
				String weekId = DateUtil.getWeekCode(new Date());
				UserTimelineDTO userTimelineDTO =  getSessionUserTimelineDTO();
				userTimelineDTO.setCurrentWeekId(weekId);
				userTimelineDTO.setWeekId(weekId);
				sessionMap.put("userTimelineDTO", userTimelineDTO);
				//TimeLineScheduler.getInstance().triggerScheduler();
			}
			return LOGINSUCCESS;
		} else {
			super.addActionError("User does not exist.");
			removeSessionValues();
			return ERROR;
		}
	}

	private void removeSessionValues() {
		sessionMap.remove("isUserLoggedIn");
		sessionMap.remove("user");
		sessionMap.remove("admin");
		sessionMap.remove("pendingUsers");
		sessionMap.remove("approvedUsers");
		sessionMap.remove("track");
		sessionMap.remove("config");
	}

	private void refreshDetails() {
		List<User> pendingUserList = userDAO.pendingListUser("Pending");
		sessionMap.put("pendingUsers", MappingUtil.convertUserListToMap(pendingUserList));
		List<User> approvedUserList = userDAO.pendingListUser("Approved");
		sessionMap.put("approvedUsers", MappingUtil.convertUserListToMap(approvedUserList));
		List<Track> trackList = trackDAO.listTrack();
		sessionMap.put("track", MappingUtil.convertTrackListToMap(trackList));
		List<Shift> shiftList = shiftDAO.listShift();
		sessionMap.put("shift", MappingUtil.convertShiftListToMap(shiftList));
		Config config = configDAO.list();
		sessionMap.put("config", config);
		if (sessionMap.get("lastFiveWeekIdList") == null) {
			List<String> lastFiveWeekIdList = DateUtil.getLastFiveWeekIds(new Date());
			sessionMap.put("lastFiveWeekIdList", lastFiveWeekIdList);
		}
	}
	
	public String registerUser () {
		List<Track> trackList = trackDAO.listTrack();
		sessionMap.put("track", MappingUtil.convertTrackListToMap(trackList));
		return SUCCESS;
	}
	public String logout(){
		removeSessionValues();
		return SUCCESS;
	}
	public String add()
	{
		validate();
		if (getActionErrors() != null && !getActionErrors().isEmpty()) {
			return ERROR;
		}
		
		if (userDAO.isUserAlreadyExist(user.getEmailId())) {
			super.addActionError("User already exist");
			return ERROR;
		}
		user.setCompOffCount("0");
		user.setShiftCount("0");
		user.setStatus("Pending");
		//user.setPassword(Encrypt.encryptString(user.getPassword()));
		userDAO.saveUser(user);
		refreshDetails();
		user = new User();
		return SUCCESS;
	}
	public String edit()
	{
		String emailId = (String) request.get("emailId");
		User userInfo = userDAO.getUser(emailId);
		if (userInfo != null) {
			sessionMap.put("editUserInfo", userInfo);
			return SUCCESS;
		}
		return ERROR;
	}
	public String approveUser()
	{
		String emailId = (String) request.get("emailId");
		User userInfo = userDAO.getUser(emailId);
		if (userInfo != null) {
			userInfo.setStatus("Approved");
			user = userInfo;
			update();
			return SUCCESS;
		}
		return ERROR;
	}
	
	public String update()
	{
		validate();
		
		if (getActionErrors() != null && !getActionErrors().isEmpty()) {
			return ERROR;
		}
		if (StringUtil.isEmpty(user.getPassword()) && sessionMap.get("editUserInfo") != null) {
			User u = (User) sessionMap.get("editUserInfo");
			user.setPassword(u.getPassword());
			user.setConfPassword(u.getPassword());
		}
		userDAO.updateUser(user);
		refreshDetails();
		sessionMap.remove("editUserInfo");
		return SUCCESS;
	}
	
	public String forgotPassword()
	{
		String emailId = (String) request.get("emailId");
		User userInfo = userDAO.getUser(emailId);
		if (userInfo == null) {
			return ERROR;
		} else {
			List<String> list = new ArrayList<String>();
			list.add(emailId);
			String emailFrom = ApplicationConfiguraion.getPropertyValue("scheduleEmailFrom");
			String htmlMessage = ApplicationConfiguraion.getPropertyValue("forgotEmailBody");
			htmlMessage = MessageFormat.format(htmlMessage, userInfo.getPassword());
			String forgotEmailSubject = ApplicationConfiguraion.getPropertyValue("forgotEmailSubject");
			EmailManager.sendMessage(htmlMessage, forgotEmailSubject , list, emailFrom);
			return SUCCESS;
		}
		
		
	}
	
	public String delete()
	{
		String emailId = (String) request.get("emailId");
		User userInfo = userDAO.getUser(emailId);
		userDAO.deleteUser(userInfo);
		refreshDetails();
		return SUCCESS;
	}
	
	public UserTimelineDTO getSessionUserTimelineDTO () {
		UserTimelineDTO userTimelineDTO = (UserTimelineDTO) sessionMap.get("userTimelineDTO");
		if (userTimelineDTO == null) {
			userTimelineDTO = new UserTimelineDTO();
		}
		return userTimelineDTO;
	}
	
	public String list()
	{
		userList = userDAO.listUser();
		return SUCCESS;
	}
		
	public String pendinglist()
	{
		userList = userDAO.pendingListUser("Pending");
		return SUCCESS;
	}
	
	public User getUser() {
		return user;
	}

	public void setUser(User user) {
		this.user = user;
	}

	public List<User> getPendingUserList() {
		return pendingUserList;
	}

	public void setPendingUserList(List<User> pendingUserList) {
		this.pendingUserList = pendingUserList;
	}

	public List<User> getUserList() {
		return userList;
	}

	public void setUserList(List<User> userList) {
		this.userList = userList;
	}
	@Override
	public void setSession(Map<String, Object> map) {
		this.sessionMap = map;
	}
	public Map<String, Object> getSession() {
		 return sessionMap;
	}

	@Override
	public void setRequest(Map<String, Object> arg0) {
		this.request = arg0;
		
	}

}
